package com.chinadaas.hangzhou.archetypeweb.util;

import com.chinadaas.framework.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;

/**
 * @author: XiaoDong.Xie
 * @create: 2021-08-05 13:37
 * @description:
 */
@Repository
public class ElasticDao {

    private Logger log = LoggerFactory.getLogger(ElasticDao.class);

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 查询请求
     *
     * @param index
     * @return
     */
    public SearchResponse query(SearchRequest searchRequest, String index) {
        try {
            return restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("查询ES异常:{}", e.getMessage());
            throw new BusinessException("查询ES失败");
        }
    }

    /**
     * 只查询统计数据
     *
     * @param boolQueryBuilder [过滤参数]
     * @param aggregation      [统计参数]
     * @param index            [索引]
     * @return SearchResponse
     */
    public SearchResponse countApiLog(BoolQueryBuilder boolQueryBuilder,
                                      TermsAggregationBuilder aggregation,
                                      String index) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
                .size(0)
                .aggregation(aggregation).query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(index).source(sourceBuilder);

        try {
            return restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (ElasticsearchStatusException e) {
            log.warn("ES查询错误：{}", e.getMessage());
            return null;
        } catch (IOException e) {
            log.error("查询ES异常:{}", e.getMessage());
            throw new BusinessException("查询ES失败");
        }
    }
}
